import json
import platform
from subprocess import CompletedProcess, run
from typing import List, Optional, Tuple
from urllib.parse import unquote, urlparse


def get_path_from_uri(uri: str) -> str:
    """Convert file uri to file path."""

    path = unquote(urlparse(uri).path)

    if platform.system() == 'Windows':
        if path.startswith('/'):
            return path[1:]
    return path


def read_builtin_cmds(path: str) -> dict:
    """Read builtin commands document into memory."""

    with open(path, encoding='utf-8') as doc:
        doc_content = doc.read()
        return json.loads(doc_content)


Modules = List[str]
Policies = List[str]
Variables = List[str]
Properties = List[str]


def get_builtin_entries() -> Optional[Tuple[Modules, Policies, Variables, Properties]]:
    args = ['cmake', '--help-module-list', '--help-policy-list', '--help-variable-list', '--help-property-list']
    res: CompletedProcess = run(args, capture_output=True, text=True, encoding='utf-8')
    if res.returncode:
        return None
    modules, policies, variables, properties = res.stdout.strip().split('\n\n\n')
    return modules.split('\n'), policies.split('\n'), variables.split('\n'), properties.split('\n')


class GetHelpDocError(Exception):
    def __repr__(self):
        return 'Failed to run cmake --help-<...>-list command'
